package com.banwoqiche.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @time: 2022-03-30 09:34
 */
@Component
@EnableWebSecurity
//开启注解进行权限判断
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, proxyTargetClass = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    private MySecurityFailHandler mySecurityFailHandler;
    private MySecuritySuccessHandler mySecuritySuccessHandler;
    private MySecurityService mySecurityService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public void setMySecurityFailHandler(MySecurityFailHandler mySecurityFailHandler) {
        this.mySecurityFailHandler = mySecurityFailHandler;
    }

    @Autowired
    public void setMySecuritySuccessHandler(MySecuritySuccessHandler mySecuritySuccessHandler) {
        this.mySecuritySuccessHandler = mySecuritySuccessHandler;
    }

    @Autowired
    public void setMySecurityService(MySecurityService mySecurityService) {
        this.mySecurityService = mySecurityService;
    }

    @Autowired
    public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //我们就知道了数据库中的密码
        auth.userDetailsService(mySecurityService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()//认证请求
                .and().formLogin()//sprringsecurity给我们提供了一个默认的登录页面,默认地址就是/login, 我们可以改
                .loginPage("/login.html")//自定义登录页面
                .successHandler(mySecuritySuccessHandler)//自定义成功
                .failureHandler(mySecurityFailHandler)
                .permitAll()/
                .and().logout()
                .and().authorizeRequests()
                .anyRequest().authenticated();//除了上面单独配置的其他地址,必须登录才可以访问,是否需要登录取决于业务
    }
}